package com.freeheart.aop.log.logscan;

import com.freeheart.aop.AopOperationUtils;
import com.freeheart.aop.log.LogInterceptor;
import com.freeheart.aop.log.LogScanManager;
import com.freeheart.aop.log.log.LogAutoConfiguration;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;

import java.util.Set;

@ConditionOnLogScan
@AutoConfigureAfter(LogAutoConfiguration.class)
public class LogScanAutoConfiguration {


    @Bean
    public Advisor logAdvisor(LogInterceptor logInterceptor) {
        // 理应不会为空。@ConditionOnLogScan注解决定LogScanManager里面一定有值。
        if (!LogScanManager.hasBasePackages()) {
            throw new IllegalArgumentException("未找到@LogScan注解的有效的basePackages属性，无法进行日志增强");
        }
        Set<String> basePackages = LogScanManager.getBasePackagesAndRemove();
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        String pointCut = AopOperationUtils.packages2AspectJPointCutExpression(basePackages);
        advisor.setExpression(pointCut);
        advisor.setAdvice(new LogScanAdvice(logInterceptor));
        return advisor;
    }


}
